from rest_framework import serializers
from apps.system.serializers import UploadSerializer
from apps.member.comments.models import Comment
from apps.member.comments.serializers import CommentSerializers
from apps.member.models import MemberRecord
from .models import Diary


class DiarySerializer(serializers.ModelSerializer):
    image = serializers.SerializerMethodField()
    comments = serializers.SerializerMethodField()
    is_collect = serializers.SerializerMethodField()
    is_like = serializers.SerializerMethodField()

    def get_is_like(self, obj):
        user = self.context['request'].user
        if user.is_authenticated:
            member_record = MemberRecord.objects.filter(content_type=Diary.get_content_type(), object_id=obj.id,
                                                        member=user, operate=MemberRecord.LIKE).first()
            if member_record:
                return True
        return False

    def get_is_collect(self, obj):
        user = self.context['request'].user
        if user.is_authenticated:
            member_record = MemberRecord.objects.filter(content_type=Diary.get_content_type(), object_id=obj.id,
                                                        member=user, operate=MemberRecord.COLLECT).first()
            if member_record:
                return True
        return False

    def get_comments(self, obj):
        comments = Comment.objects.filter(content_type=Diary.get_content_type(), object_id=obj.id, parent=None)
        return CommentSerializers(instance=comments, many=True).data

    def get_image(self, obj):
        return UploadSerializer(obj.images, many=True).data

    class Meta:
        model = Diary
        fields = '__all__'
